import {onMounted, onUnmounted, ref} from 'vue';
import {api} from "@jzl/api";
import _ from "lodash";

export function useApps() {

  const loading = ref(false)
  const appGroups = ref([]);
  const apps = ref([]);

  const loadApps = async () => {
    loading.value = true;
    let ret = await api.admin.getMyApps(0);  // 123
    let appGroupsData = _.get(ret, "dirs") || [];
    let appsData = _.get(ret, "apps") || [];
    let notGroupsApps = [];
    let def = {
      group_id: -1,
      group_name: '未分组',
      type: 3,
      subs: []
    };

    for (let i = 0; i < appsData.length; i++) {
      let appData = appsData[i];
      let parent_id = _.get(appData, "parent_id");
      let g = _.find(appGroupsData, { group_id: parent_id });
      if (g) {
        if (!g.subs) g.subs = [];
        g.subs.push(appData);
      } else {
        notGroupsApps.push(appData);
      }
    }
    if (notGroupsApps && notGroupsApps.length) {
      def.subs = notGroupsApps;

      appGroupsData.push(def);
    }

    loading.value = false;
    apps.value = appsData;
    appGroups.value = appGroupsData;

    return {
      apps,
      appGroups
    }
  };

  onMounted(async () => {
    await loadApps();
  })

  return {
    loading,
    apps,
    appGroups,
    loadApps
  }
}

export default useApps;
